//
//  thirdViewController.m
//  HappilyLoan
//
//  Created by 纵情向前 on 2017/4/21.
//  Copyright © 2017年 zongqingxiangqian. All rights reserved.
//

#import "thirdViewController.h"
#import "SecondTableViewCell.h"
#import "PublicClass.h"
#import "MJRefresh.h"
#import "ZFNewsRequestModel.h"
#import "AlertBoxView.h"
#import "UIImageView+WebCache.h"
#import <NSObject+YYModel.h>
#import "SecondDetailModel.h"
#import "SecondModel.h"
#import "SecondListModel.h"
#import "ZFHttpTool.h"
@interface thirdViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *TableView;
@property (nonatomic, strong) NSMutableArray * mydataArray;
@property (nonatomic, strong) NSArray * dataArray;
@property (nonatomic, assign) NSInteger index;
@property(nonatomic,strong)AlertBoxView *alertBox;

@end

@implementation thirdViewController
- (NSMutableArray *)mydataArray{
    if (!_mydataArray) {
        _mydataArray = [[NSMutableArray alloc]init];
    }
    return _mydataArray;
}
- (NSArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSArray alloc]init];
    }
    return _dataArray;
}
- (void)viewWillAppear:(BOOL)animated{
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = YES;
    
    [self.view addSubview:self.TableView];
    self.index = 1;
    __weak typeof(self) weakSelf = self;
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        weakSelf.index = 1;
        [self loadDataThirdRefresh];
        //[self.myTableView reloadData];
        
    }];
    _TableView.mj_header = header;
    MJRefreshAutoNormalFooter * footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        weakSelf.index += 1;
        [self loadDataThirdRefresh];
        //[self.myTableView reloadData];
        
    }];
    footer.automaticallyRefresh = NO;
    _TableView.mj_footer = footer;
    _TableView.mj_footer.hidden = YES;
    [_TableView.mj_header beginRefreshing];
    // Do any additional setup after loading the view from its nib.
}

#pragma mark - TableView
- (UITableView *)TableView{
    if (!_TableView) {
        
        _TableView = [[UITableView alloc] init];
        _TableView.frame = CGRectMake(0,0,MAINSCREEN_WIDTH,ADAPTATION_HEIGHT((667-64-48)));
        _TableView.delegate = self;
        _TableView.dataSource = self;
        _TableView.backgroundColor = [UIColor whiteColor];
        [_TableView registerClass:[SecondTableViewCell class] forCellReuseIdentifier:@"defaultCell"];
        _TableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _TableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
//        _TableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(action_Reload)];
//        _TableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(action_Load)];
    }
    return _TableView;
}
//#pragma mark - 刷新
//- (void)action_Reload {
//    //刷新
//    [self.TableView.mj_header beginRefreshing];
//    
//    [self performSelector:@selector(endRefresh) withObject:nil afterDelay:1.1];
//}
//- (void)endRefresh {
//    [self.alertBox appearAndDisappearAlertWithString:@"暂无更多数据！"];
//    [self.TableView.mj_header endRefreshing];
//    [self.TableView.mj_footer endRefreshing];
//}
//-(void)action_Load{
//    [self performSelector:@selector(endRefresh) withObject:nil afterDelay:1.1];
//}
#pragma mark--UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.mydataArray.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 93/H;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SecondTableViewCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!Cell) {
        Cell = [[SecondTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"defaultCell"];
    }

    SecondDetailModel *listModel = [SecondDetailModel yy_modelWithDictionary:self.mydataArray[indexPath.row]];
    if (listModel == nil) {
        [_alertBox appearAndDisappearAlertWithString:@"暂无更多消息"];
        
    }else{
        NSString *updateStr = listModel.create_time;
        NSDate *updateDate = [NSDate dateWithTimeIntervalSince1970:[updateStr doubleValue]/1000];
        NSString *updateString = [NSString stringWithFormat:@"%@",updateDate];
        Cell.titleLabel.text = listModel.activity_content;
        Cell.timeLabel.text = [updateString substringToIndex:10];
        Cell.readNumberLabel.text = listModel.activity_title;
        NSURL *url = [NSURL URLWithString:listModel.activity_pic];
        [Cell.detailImage sd_setImageWithURL:url];
    }

    
    //Cell图片
    UILabel *label = [[UILabel alloc] init];
    label.frame = CGRectMake(20/W, 92/H, (375-40)/W, 1);
    label.backgroundColor = [UIColor lightGrayColor];
    [Cell addSubview:label];
    
    
    Cell.selectionStyle = UITableViewCellSelectionStyleNone;
    //    Cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//右箭头
    return Cell;
}

-(void)loadDataThirdRefresh{
    NSString *str = @"http://192.168.1.24";
    NSDictionary * dict = @{@"activity_type":@"3",@"currentPage":[NSString stringWithFormat:@"%ld",(long)self.index]};
    [ZFHttpTool postWithURL:[NSString stringWithFormat:@"%@/system/findActivityInfoList",str] params:dict bodyStr:@"" success:^(id responseObject) {
        SecondModel *model = [SecondModel yy_modelWithJSON:responseObject];
        if (model.is_alert != 0) {
            [_alertBox appearAndDisappearAlertWithString:[NSString stringWithFormat:@"%@",model.msg]];
        }
        if ([model.code integerValue] == 1) {
            _TableView.mj_footer.hidden = NO;
            SecondListModel *listModel = [SecondListModel yy_modelWithDictionary:model.data];
            self.dataArray = listModel.list;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                if (self.index == 1) {
                    if (self.mydataArray.count > 0 ) {
                        [self.mydataArray removeAllObjects];
                    }
                }
                [self.mydataArray addObjectsFromArray:self.dataArray];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (self.index == 1) {
                        [_TableView.mj_header endRefreshing];
                    }else{
                        [_TableView.mj_footer endRefreshing];
                    }
                    if (self.mydataArray.count==0) {
                        [_alertBox appearAndDisappearAlertWithString:@"暂无更多内容"];
                    }
                    [self.TableView reloadData];
                });
                
            });
            
        }else{
            _TableView.mj_footer.hidden = NO;
            if (self.index == 1) {
                
                [self.mydataArray removeAllObjects];
                [_TableView.mj_header endRefreshing];
            }else{
                
                [_TableView.mj_footer endRefreshing];
            }
            [self.TableView reloadData];
        }
    } failure:^(NSError *error) {
        [_alertBox appearAndDisappearAlertWithString:@"网络连接失败"];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (self.index == 1) {
                [_TableView.mj_header endRefreshing];
                
            }else{
                
                self.index -=1;
                [_TableView.mj_footer endRefreshing];
                
            }
            [_TableView reloadData];
        });
        
        [_TableView reloadData];
    }];

//    [ZFNewsRequestModel requestFindActivityType:@"3" CurrentPage:@"1" SucessBlock:^(NSDictionary *dict) {
//        NSArray *array = dict[@"data"][@"list"];
//        NSMutableArray *infoArray = [NSMutableArray array];
//        for (NSDictionary *dic in array) {
//            StrategyModel *cellInfo = [StrategyModel getStrategyInfoDictionary:dic];
//            [infoArray addObject:cellInfo];
//        }
//        self.mydataArray = infoArray;
//        
//    } failureBlock:^(NSInteger failSign) {
//        NSLog(@"gonglu攻略失败");
//        [_alertBox appearAndDisappearAlertWithString:@"网络连接失败"];
//    }];
}
#pragma mark -- getter / setter
- (AlertBoxView *)alertBox
{
    if (!_alertBox) {
        _alertBox = [[AlertBoxView alloc] init];
    }
    return _alertBox;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
